package org.fanximall.erp.product.application.valid;

import org.apache.commons.lang3.StringUtils;
import org.fanximall.erp.common.utils.SpringUtils;
import org.fanximall.erp.product.domain.repository.DictRepository;


import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.*;

/**
 * @version :  V1.0 created in 2024/4/3
 * @author  :  william
 * 校验字典值是否存在
 */
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = {ValidationDictValue.Validator.class})
public @interface ValidationDictValue {

    //默认错误信息
    String message() default "字典值不存在";

    //分组
    Class<?>[] groups() default {};

    //负载
    Class<? extends Payload>[] payload() default {};

    class Validator implements ConstraintValidator<ValidationDictValue,String> {
        @Override
        public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
            DictRepository repository = SpringUtils.getBean(DictRepository.class);
            if (StringUtils.isNotBlank(value)) {
                String dictName = repository.getDictName(value);
                return StringUtils.isNotBlank(dictName);
            }
            return true;
        }


    }
}
